﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace zielonka.co.uk.extensions.Generic.class_
{
    /*example
     * 
       public class Customer : MXmlSerializable 
       {
          public string Name { get; set; }
          public bool Preferred { get; set; }
        }
        
     // And the usage is simply:

        var customer = new Customer { 
        Name = "Guybrush Threepwood", 
        Preferred = true };
        var xml = customer.ToXml();
     
      */
    public interface MXmlSerializable { }

    public static class XmlSerializable
    {
        public static string ToXml(this MXmlSerializable self)
        {
            if (self == null) throw new ArgumentNullException();
            var serializer = new XmlSerializer(self.GetType());
            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, self);
                return writer.GetStringBuilder().ToString();
            }
        }
        public static T FromXml<T>(string xml) where T : MXmlSerializable
        {
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(new StringReader(xml));
        }
    }
}
